package com.it.sun.redismq.context;

import cn.hutool.core.util.ArrayUtil;
import com.it.sun.redismq.annotation.MessageConsumer;
import com.it.sun.redismq.annotation.MessageHandler;
import com.it.sun.redismq.annotation.MessageListener;
import com.it.sun.redismq.handler.AbstractMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName com.it.sun.springboot.course.config.ApplicationContextRunner
 * @Author sun
 * @Date 2021/1/28 10:21
 * @Version V1.0
 * Description  <请输入一句话描述该类功能>
 * Copyright (C) xxxx  since 2021/1/28
 */
@Component
@Slf4j
public class MessageConsumerStater implements ApplicationRunner, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) {
        Map<MessageListener.Mode, AbstractMessageHandler> invokers = getInvokers ();
        applicationContext.getBeansWithAnnotation (MessageConsumer.class).values ().parallelStream ().forEach (consumer -> {
            Method[] methods = consumer.getClass ().getMethods ();
            if (ArrayUtil.isNotEmpty (methods)) {
                Arrays.stream (methods).parallel ().forEach (method -> startMessageListener (method, invokers));
            }
        });
    }

    private void startMessageListener(Method method, Map<MessageListener.Mode, AbstractMessageHandler> invokers) {
        MessageListener listener = method.getAnnotation (MessageListener.class);
        if (null == listener) {
            return;
        }
        MessageListener.Mode mode = listener.mode ();
        AbstractMessageHandler invoker = invokers.get (mode);
        if (invoker == null) {
            log.error ("invoker is null");
            return;
        }
        invoker.invokeMessage (method);
    }

    private Map<MessageListener.Mode, AbstractMessageHandler> getInvokers() {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation (MessageHandler.class);
        Map<MessageListener.Mode, AbstractMessageHandler> collect =
                beansWithAnnotation.values ().stream ().collect (Collectors
                        .toMap (k -> k.getClass ().getAnnotation (MessageHandler.class).value (), k -> (AbstractMessageHandler) k));
        return collect;
    }

    public MessageConsumerStater() {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
